import {lon2xy} from "./math"
import * as THREE from 'three';
// 水面颜色贴图
var texture = new THREE.TextureLoader().load('/水面.jpg');
var normalTexture = new THREE.TextureLoader().load('/normal.jpg');
// 设置阵列模式为 RepeatWrapping
texture.wrapS = THREE.RepeatWrapping
texture.wrapT = THREE.RepeatWrapping
// 水面区域比较大的话，纹理贴图不能无限大，一般可以通过阵列解决。
texture.repeat.set(20, 20); // x和y方向阵列纹理贴图
normalTexture.wrapS = THREE.RepeatWrapping
normalTexture.wrapT = THREE.RepeatWrapping
normalTexture.repeat.set(20, 20);
// 流动动画 最简单方式就是使用texture的offset属性实现  也可以用更麻烦的shader实现
var t = 0;

function flowAnimation() {
  requestAnimationFrame(flowAnimation);
  t += 0.02;
  var y = 0.05 * Math.sin(t);
  texture.offset.x = y;
  texture.offset.y = y;
}
flowAnimation();
const WaterShapeMesh = function(pointsArr){
    var shapeArr = []
    pointsArr.forEach(pointsArr=>{
      var vector2Arr = []
      pointsArr[0].forEach(elem=>{
        var xy = lon2xy(elem[0],elem[1])
        vector2Arr.push(new THREE.Vector2(xy.x,xy.y))
      })
      shapeArr.push(new THREE.Shape(vector2Arr))
    })
   const geometry = new THREE.ShapeGeometry(shapeArr)
    var pos = geometry.attributes.position; //顶点位置坐标 
    var uv = geometry.attributes.uv; //顶点UV坐标
    var count = pos.count; //顶点数量
    var xArr = []; //多边形polygon的所有x坐标
    var yArr = []; //多边形polygon的所有y坐标
    for(var i = 0;i<count;i++){
      xArr.push(pos.getX(i));
      yArr.push(pos.getY(i));
    }
    // minMax()计算polygon所有坐标,返回的极大值、极小值
  var [xMin, xMax] = minMax(xArr);
  var [yMin, yMax] = minMax(yArr);
    //   uv的矩形大小
    var xL = xMax - xMin;
    var yL = yMax - yMin;
    for(var j = 0 ;j<count;j++){
        var uvx = (pos.getX(j)-xMin)/xL
        var uvy = (pos.getY(j)-yMin)/yL
        uv.setXY(j,uvx,uvy)
    }
    const material =  new THREE.MeshPhongMaterial({
      map: texture,
      normalMap: normalTexture,
      normalScale: new THREE.Vector2(5, 5)
    })
    const mesh = new THREE.Mesh( geometry, material);
    return mesh
  }
  //   多边形坐标进行排序
function minMax(arr) {
    // 数组元素排序
    arr.sort(compareNum);
    // 返回极小值和极大值
    return [arr[0], arr[arr.length - 1]]
  }
// 数组排序规则
function compareNum(num1, num2) {
    if (num1 < num2) {
        return -1;
    } else if (num1 > num2) {
        return 1;
    } else {
        return 0;
    }
    }
  export {WaterShapeMesh}